package com.rslai.commons.validator.jsonvalidator.validators;

import com.alibaba.fastjson.JSON;
import com.rslai.commons.validator.jsonvalidator.JsonValidator;
import com.rslai.commons.validator.jsonvalidator.matchers.JsonAssert;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * JSON校验器，否包含校验器
 */
public class HasItemValidator extends Validator {
    private static final Logger logger = LoggerFactory.getLogger(HasItemValidator.class);

    public static final String VALIDATOR_NAME = "hasItem";
    private List<String> schemas = new ArrayList<String>();

    /**
     * 构造函数
     * @param params params
     */
    public HasItemValidator(List<Object> params) {
        if (params != null) {
            for (Object o : params) {
                schemas.add((String) o);
            }
        }
    }

    /**
     * 校验JSON对象
     * @param object 待验证的JSON对象
     */
    @Override
    public void doValidate(Object object) {
        Assert.assertThat("hasItem 校验器不能传入空对象。", object, Matchers.notNullValue());
        List<Object> list = new ArrayList<Object>();
        if (object.getClass().isArray()) {
            Object[] objects = (Object[]) object;
            Collections.addAll(list, objects);
        } else if (object instanceof List) {
            list.addAll((List<?>) object);
        } else {
            Assert.fail("hasItem 校验器不支持此类 <" + object.getClass() + ">");
        }
        for (String schema : schemas) {
            boolean isMatched = false;
            for (Object o : list) {
                try {
                    JsonValidator.validate(schema, JSON.toJSONString(o));
                    isMatched = true;
                } catch (Throwable e) {
                    // logger.error("hasItem 校验器校验失败。", e); 某一个对比失败但不想打印错误日志
                }
            }
            if (!isMatched) {
                JsonAssert.fail(getCurrentKeyPath() + "数组中不包含期望的元素", schema, list, VALIDATOR_NAME);
            }
        }
    }

    /**
     * 返回校验名称
     * @return 校验名称
     */
    @Override
    public String name() {
        return VALIDATOR_NAME;
    }
}
